package main

/*
	API 总入口
*/

import (
	"Video-go/api/session"
	"net/http"

	// httprouter 是一个高性能、可扩展的HTTP路由
	"github.com/julienschmidt/httprouter"
)

// http 中间件
type middleWareHandler struct {
	r *httprouter.Router
}

// 工厂函数
func NewMiddleWareHandler(r *httprouter.Router) http.Handler {
	m := middleWareHandler{}
	m.r = r
	return m
}

// ServeHTTP 实现http.Handler 接口
func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	validateUserSession(r) // 效验session
	m.r.ServeHTTP(w, r)
}

// RegisterHandlers 注册路由
func RegisterHandlers() *httprouter.Router {

	router := httprouter.New()
	// 注册
	router.POST("/user", CreateUser)
	// 登录
	router.POST("/user/:user_name", Login)
	// 获取用户信息
	router.GET("/user/:username", GetUserInfo)
	// 添加新的视频
	router.POST("/user/:username/videos", AddNewVideo)
	// 获取所有视频
	router.GET("/user/:username/videos", ListAllVideos)
	// 删除一个视频
	router.DELETE("/user/:username/videos/:vid-id", DeleteVideo)
	// 发送一个评论
	router.POST("/videos/:vid-id/comments", PostComment)
	// 显示所有评论
	router.GET("/videos/:vid-id/comments", ShowComments)

	return router
}
func Prepare() {
	session.LoadSessionFromDB()
}

func main() {
	Prepare()
	r := RegisterHandlers()
	mh := NewMiddleWareHandler(r)
	http.ListenAndServe(":8000", mh)
}
